package com.biostime.qdingding.modules.qd.push;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.biostime.qdingding.common.config.Global;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;

/**
 * 推送服务
 * @author phil
 * @version 2015-12-14
 */
public class PushService {
	
	protected static Logger logger = LoggerFactory.getLogger("msg"); //日志对象
	
	//sharemarking
	/*public static String appId = "C3XRMaPvty790MlCJGtZ97";
	public static String appSecret = "KyzDbwHxJ09HD6fWtYOs29";
	public static String appkey = "jnTVTNXsHK6pdBhfFskxb8";
	public static String masterSecret = "fYmS1hyEkq9BikU84N9Pu4";
	*/
	
	//biostime
	/*public static String appId = "5pGVlSorfc9TiXjEcARu87";
	public static String appSecret = "cLzLMqLbE77E6yWTufo6k9";
	public static String appkey = "j5PDRhxkoL6ozrbKKdk1K";
	public static String masterSecret = "U1p9VvGmAyAkxyVbztM1KA";
	*/
	
	public static String appId = Global.getConfig("push.appId");
	public static String appSecret = Global.getConfig("push.appSecret");
	public static String appkey = Global.getConfig("push.appkey");
	public static String masterSecret = Global.getConfig("push.masterSecret");
	
	public static String host = Global.getConfig("push.host");
	//public static String CID = "9b2c07289c25f5c516e36fb2acf92110";
	
	public static void pushMessageToSingle(String userId, PushMessage msg){
		
		IGtPush push = new IGtPush(host,appkey, masterSecret);
		
		try {
			SingleMessage message = new SingleMessage();
			message.setOffline(true);
			message.setOfflineExpireTime(24 * 1000 * 3600);
			message.setData(transmissionTemplate(msg));
			
			Target target = new Target();
			target.setAppId(appId);
			//target1.setClientId(CID); //通过ClientId发送
			target.setAlias(userId); //通过别名发送
			try {
				IPushResult ret = push.pushMessageToSingle(message, target);
				logger.info("消息["+userId+","+msg.getId()+"]发送正常：" + ret.getResponse().toString());
				//System.out.println("正常：" + ret.getResponse().toString());
			} catch (RequestException e) {
				IPushResult ret = push.pushMessageToSingle(message, target);
				logger.info("消息["+userId+","+msg.getId()+"]发送异常：" + ret.getResponse().toString());
				//System.out.println("异常：" + ret.getResponse().toString());
			}
		}catch(Exception ex){
			logger.info("消息["+userId+","+msg.getId()+"]发送期间异常：" + ex.getMessage() + ex.getStackTrace());
		}
	}
	
	public static void pushMessageToApp(String userId, PushMessage msg){
		IGtPush push = new IGtPush(host,appkey, masterSecret);
		
		try {
			AppMessage message = new AppMessage();
			message.setOffline(true);
			message.setOfflineExpireTime(24 * 1000 * 3600);
			message.setData(transmissionTemplate(msg));
			
			List<String> appIdList = new ArrayList<String>();
			appIdList.add(appId);
			
			message.setAppIdList(appIdList);
			
			try {
				IPushResult ret = push.pushMessageToApp(message, "任务别名_toApp");
				logger.info("消息["+userId+","+msg.getId()+"]发送正常：" + ret.getResponse().toString());
				//System.out.println("正常：" + ret.getResponse().toString());
			} catch (RequestException e) {
				IPushResult ret = push.pushMessageToApp(message, "任务别名_toApp");
				logger.info("消息["+userId+","+msg.getId()+"]发送异常：" + ret.getResponse().toString());
				//System.out.println("异常：" + ret.getResponse().toString());
			}
		}catch(Exception ex){
			logger.info("消息["+userId+","+msg.getId()+"]发送期间异常：" + ex.getMessage() + ex.getStackTrace());
		}
	}

	public static TransmissionTemplate transmissionTemplate(PushMessage pushMessage) throws Exception {

		/*PushMessage msg = new PushMessage();
		msg.setCategory("course");
		msg.setTitle("标题");
		msg.setContent("内容");
		msg.setCleared(true);
		msg.setRedirect("http://www.baidu.com");
		msg.setTime(new Date());*/
		
		ObjectMapper mapper = new ObjectMapper();
		
		TransmissionTemplate template = new TransmissionTemplate();
		template.setAppId(appId); //设定接收的应用
		template.setAppkey(appkey); //用于鉴定身份是否合法
		template.setTransmissionType(2); //收到消息是否立即启动应用，1为立即启动，2则广播等待客户端自启动
		template.setTransmissionContent(mapper.writeValueAsString(pushMessage)); //透传内容，不支持转义字符
		//template.setDuration("2015-01-16 11:40:00", "2015-01-16 12:24:00"); //设置定时展示时间
		//template.setPushInfo("", 1, "", "", "", "", "", "");
		
		//bug://IOS推送－通知栏无标题
		pushMessage.setContent(String.format("%s, %s", pushMessage.getTitle(), pushMessage.getContent()));
		
		//**********APN简单推送********//
		//https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html
		APNPayload apnpayload = new APNPayload();
		APNPayload.SimpleAlertMsg alertMsg = new APNPayload.SimpleAlertMsg(pushMessage.getContent());
		apnpayload.setAlertMsg(alertMsg);
		apnpayload.setBadge(1);
		apnpayload.setSound("default");
		apnpayload.setContentAvailable(1);
		//apnpayload.setCategory("ACTIONABLE");
		apnpayload.addCustomMsg("msg", mapper.writeValueAsString(pushMessage));
		template.setAPNInfo(apnpayload); //iOS推送使用该字段，详见iOS模板说明
		
		//************APN高级推送*******************//
		/*APNPayload apnpayload = new APNPayload();
		apnpayload.setBadge(4);
		apnpayload.setSound("test2.wav");
		apnpayload.setContentAvailable(1);
		apnpayload.setCategory("ACTIONABLE");
		APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
		alertMsg.setBody("body");
		alertMsg.setActionLocKey("ActionLockey");
		alertMsg.setLocKey("LocKey");
		alertMsg.addLocArg("loc-args");
		alertMsg.setLaunchImage("launch-image");
		// IOS8.2以上版本支持
		alertMsg.setTitle("Title");
		alertMsg.setTitleLocKey("TitleLocKey");
		alertMsg.addTitleLocArg("TitleLocArg");

		apnpayload.setAlertMsg(alertMsg);
		template.setAPNInfo(apnpayload);*/
		
		return template;
	}
}
